<!-- 成员调出 -->
<template>
  <div class="del_user">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="200">
      <Row :gutter="16">
        <Col span="22">
          <FormItem label="调出人员：">
            <span>{{ RowUserData.userName }}</span>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col span="22">
          <FormItem label="成员角色：">
            <span>{{ RowUserData.roleNames ? RowUserData.roleNames.join(',') : '-' }}</span>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col span="22">
          <FormItem label="调出类型：" prop="changeType">
            <Select
              v-model="formValidate.changeType"
              placeholder="请选择"
              class="cityConfigArea_moudle_select">
              <Option
                v-for="(item, index) in onCaseChangeArr"
                :key="index"
                :value="item.key"
                @click.native="handleClickchangeType(item.key)">
                {{ item.value }}
              </Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row
        :gutter="16"
        v-if="isTaskUsertipsShow && (formValidate.changeType == '0' || formValidate.changeType == '3')">
        <Col span="18" class="tips">
          <Icon type="md-alert" class="tips_icon" />
          {{ RowUserData.userName }}是任务责任人，调离后需重新设置责任人
          <span class="AssignCustomers_name" @click="totaskOwner">手动调整</span>
        </Col>
      </Row>
      <!-- 调离 -->
      <div v-if="formValidate.changeType === '0'">
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="调出后是否保留案场权限：" prop="authFlag">
              <Radio-group v-model="formValidate.authFlag">
                <Radio label="1">保留</Radio>
                <Radio label="2">不保留</Radio>
              </Radio-group>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16" v-if="tipsShow && formValidate.authFlag == 2">
          <Col span="18" class="tips">
            <Icon type="md-alert" class="tips_icon" />
            提示：{{ RowUserData.userName }}名下仍有正在服务的客户，关闭权限后其名下客户将会进入公客池。
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="调入公司：" prop="company">
              <Select
                v-model="formValidate.company"
                placeholder="请选择"
                class="cityConfigArea_moudle_select"
                filterable
                :disabled="disabledCompany">
                <Option
                  v-for="(item, index) in companyArr"
                  :key="index"
                  :value="item.orgId"
                  @click.native="handleClickcompany(item)">
                  {{ item.name }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="调入案场：" prop="targetCaseId">
              <Select
                v-model="formValidate.targetCaseId"
                placeholder="请选择"
                class="cityConfigArea_moudle_select"
                filterable>
                <Option v-for="(item, index) in caseArr" :key="index" :value="item.housesId">
                  {{ item.housesName }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="异动日期：" prop="executeDate">
              <DatePicker
                type="date"
                v-model="formValidate.executeDate"
                @on-change="formValidate.executeDate = $event"
                format="yyyy-MM-dd"
                :options="currentOptions"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </div>
      <!-- 支援 -->
      <div v-if="formValidate.changeType === '1'">
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="调入公司：" prop="company">
              <Select
                v-model="formValidate.company"
                placeholder="请选择"
                class="cityConfigArea_moudle_select"
                filterable>
                <Option
                  v-for="(item, index) in companyArr"
                  :key="index"
                  :value="item.orgId"
                  @click.native="handleClickcompany(item)">
                  {{ item.name }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="调入案场：" prop="targetCaseId">
              <Select
                v-model="formValidate.targetCaseId"
                placeholder="请选择"
                class="cityConfigArea_moudle_select"
                filterable>
                <Option v-for="(item, index) in caseArr" :key="index" :value="item.housesId">
                  {{ item.housesName }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="开始进场日期：" prop="executeDate">
              <DatePicker
                type="date"
                @on-change="formValidate.executeDate = $event"
                format="yyyy-MM-dd"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </div>
      <!-- 调岗 -->
      <div v-if="formValidate.changeType === '2'">
        <Row :gutter="16" v-if="tipsShow">
          <Col span="18" class="tips">
            <Icon type="md-alert" class="tips_icon" />
            提示：{{ RowUserData.userName }}名下仍有正在服务的客户，关闭权限后其名下客户将会进入公客池。
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="调离日期：" prop="executeDate">
              <DatePicker
                type="date"
                @on-change="formValidate.executeDate = $event"
                format="yyyy-MM-dd"
                :options="currentOptions"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </div>
      <!-- 离职 -->
      <div v-if="formValidate.changeType === '3'">
        <Row :gutter="16" v-if="tipsShow">
          <Col span="18" class="tips">
            <Icon type="md-alert" class="tips_icon" />
            提示：{{ RowUserData.userName }}名下仍有正在服务的客户，关闭权限后其名下客户将会进入公客池。
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="22">
            <FormItem label="离职日期：" prop="executeDate">
              <DatePicker
                type="date"
                @on-change="formValidate.executeDate = $event"
                format="yyyy-MM-dd"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </div>
      <Row
        :gutter="16"
        v-if="tipsFlag && (formValidate.changeType === '2' || formValidate.changeType === '0')">
        <Col span="18" class="tips">
          <Icon type="md-alert" class="tips_icon" />
          提示：该人员今日已有异动记录，暂不可操作调动。
        </Col>
      </Row>
    </Form>
    <div class="flex flex-horizontal-end btn-operate">
      <Button @click="handleClose">取消</Button>
      <Button type="primary" @click="submitFun()" style="margin-left: 8px">确定</Button>
    </div>
  </div>
</template>
<script>
  import teamsApi from '@/biz/buildingManagement/teams'
  export default {
    props: {
      RowUserData: {
        type: Object,
        default: () => {
          return {}
        }
      }
    },
    data() {
      return {
        buildingAlias: '',
        cityName: '',
        buildingId: '',
        teamId: '',
        userMess: this.$dt.userInfo(),
        tipsShow: false,
        tipsFlag: false,
        isTaskUsertipsShow: false,
        onCaseChangeArr: [
          { key: '0', value: '调离至其他案场 (编制移出本案场)' },
          { key: '1', value: '支援其他案场 (编制保留本案场)' },
          { key: '2', value: '移出本案场 (编制移出本案场)' }
          // { key: '3', value: '离职' },
        ],
        companyArr: [], //调入公司
        companyArrAll: [], //全部公司
        caseArr: [], //调入案场
        formValidate: {
          changeType: '', //变动类型
          executeDate: null, //开盘时间
          targetCaseId: '', //调入案场id
          authFlag: '', //调出后是否保留案场权限
          company: '' //调入公司
        },
        ruleValidate: {
          changeType: [{ required: true, message: '请选择调出类型', trigger: 'change' }],
          company: [{ required: true, message: '请选择调入公司', trigger: 'change' }],
          authFlag: [
            {
              required: true,
              message: '请选择是否保留案场权限',
              trigger: 'change'
            }
          ],
          targetCaseId: [
            {
              required: true,
              message: '请选择调入案场',
              trigger: 'change',
              type: 'number'
            }
          ],
          executeDate: [
            {
              required: true,
              message: '请选择时间',
              trigger: 'blur'
            }
          ]
        },
        currentOptions: {
          disabledDate(date) {
            return date && date.valueOf() > new Date()
          }
        },
        disabledCompany: false
      }
    },
    methods: {
      submitFun() {
        this.reCustomerList().then((len) => {
          if (len) {
            if (this.formValidate.changeType == '0') {
              this.$Modal.confirm({
                title: '调离至其他案场确认',
                content:
                  '<p>' +
                  this.RowUserData.userName +
                  '名下仍有正在服务的客户，调离后其名下客户将会进入公客池。是否继续调离？</p>',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  this.submitFunOk()
                }
              })
            } else if (this.formValidate.changeType == '2') {
              this.$Modal.confirm({
                title: '移出本案场确认',
                content:
                  '<p>' +
                  this.RowUserData.userName +
                  '名下仍有正在服务的客户，移出本案场后其名下客户将会进入公客池。是否继续移出？</p>',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  this.submitFunOk()
                }
              })
            }
          } else {
            this.submitFunOk()
          }
        })
      },
      submitFunOk() {
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            let type = this.formValidate.changeType
            console.log(this.formValidate, 'formValidateAdd')
            let params = {
              changeType: this.formValidate.changeType,
              executeDate: this.formValidate.executeDate,
              operatorId: this.userMess.userId,
              sourceCaseId: this.buildingId,
              targetCaseId: this.formValidate.targetCaseId,
              teamId: this.teamId,
              teamUserId: this.RowUserData.teamUserId,
              userId: this.RowUserData.userId,
              authFlag: this.formValidate.authFlag == '1' ? true : false,
              groupId: this.RowUserData.groupId
            }
            console.log(params, '&&&&')
            teamsApi.userExitTeam(params).then((res) => {
              if (res) {
                let userRoleNames = res.join('、')
                this.unlocking('0102030200') && this.$emit('hasTrimpropor', userRoleNames)
              }
              if (type == 0) {
                this.$Message.success('成员调离信息已提交!')
              } else if (type == 1) {
                this.$Message.success('成员支援信息已提交!')
              } else if (type == 2) {
                this.$Message.success('成员已从本案场调离!')
              } else if (type == 3) {
                this.$Message.success('成员离职信息已提交，系统已将TA从本案场移出!')
              }
              this.$emit('onClose')
              this.$emit('onChangeTable')
            })
          }
        })
      },
      handleClose() {
        this.$emit('onClose')
      },
      // 查询顾问当前楼盘下的客户数
      reCustomerList() {
        return new Promise((resolve, reject) => {
          if (
            this.formValidate.changeType !== '1' &&
            (this.formValidate.authFlag == 2 || this.formValidate.authFlag == '')
          ) {
            let params = {
              buildingId: this.buildingId,
              userId: this.RowUserData.userId
            }
            teamsApi.getCustomerPoolCountByUser(params).then((res) => {
              this.tipsShow = res > 0 ? true : false
              resolve(Number(res))
            })
          } else {
            resolve(0)
          }
        })
      },
      //根据公司名称模糊查询公司
      getOrgByOrgNameArr() {
        let params = {
          buildingId: this.buildingId,
          transferType: this.formValidate.changeType == '0' ? 2 : this.formValidate.changeType == '1' ? 1 : ''
        }
        teamsApi.getOrgByOrgName({ ...params }).then((res) => {
          console.log(res)
          if (res) {
            this.companyArrAll = res
            this.companyArr = res
          }
        })
      },
      changeOrgByOrgNameArr(query) {
        if (query !== '') {
          this.companyArr = this.companyArrAll.filter(
            (item) => item.name.toLowerCase().indexOf(query.toLowerCase()) > -1
          )
        } else {
          this.companyArr = this.companyArrAll
        }
      },
      //选择完公司查询公司下的案场
      handleClickcompany(obj) {
        this.formValidate.targetCaseId = ''
        teamsApi.getBuildingByOrg({ orgId: obj.orgId }).then((res) => {
          if (res) {
            this.caseArr = res
          }
        })
      },
      handleClickchangeType(key) {
        this.formValidate = {
          executeDate: null, //开盘时间
          targetCaseId: '', //调入案场id
          authFlag: '', //调出后是否保留案场权限
          company: '' //调入公司
        }
        // if (key == '0') {
        //   this.formValidate.company = '6'
        //   this.handleClickcompany({ orgId: this.formValidate.company })
        //   this.disabledCompany = true
        // }
        this.formValidate.changeType = key
        if (this.formValidate.changeType == '1' || this.formValidate.changeType == '0') {
          this.getOrgByOrgNameArr()
        }
        // this.getOrgByOrgNameArr()
      },
      //当前成员是任务责任人
      getCurrentIsTaskUser() {
        let params = {
          userId: this.RowUserData.userId,
          buildingId: this.$dt.buildInfo().housesId
        }
        teamsApi.isTaskUser({ ...params }).then((res) => {
          this.isTaskUsertipsShow = res
        })
      },
      onChangeTaskUser(val) {
        console.log('onChangeTaskUser', val)
        this.getCurrentIsTaskUser()
      },
      totaskOwner() {
        this.$emit('openTask')
        this.$$on('changeTaskUser')
      },
      //获取最近的一条异动记录
      getUserChangeTimeLimit1() {
        teamsApi.getUserChangeTimeLimit1({ userId: this.RowUserData.userId }).then((res) => {
          if (res) {
            if (res.split(' ')[0] == this.$tool.dateFtt('yyyy-MM-dd', new Date())) {
              this.tipsFlag = true
            }
            this.currentOptions = {
              disabledDate(date) {
                return (
                  date &&
                  (date.valueOf() < Date.parse(res.split(' ')[0]) + 43200000 || date.valueOf() > new Date())
                )
              }
            }
          }
        })
      }
    },
    created() {
      let buildMess = this.$dt.buildInfo()
      this.buildingAlias = buildMess.housesName
      this.cityName = buildMess.city
      this.buildingId = buildMess.housesId
      this.teamId = this.$dt.session.get('teamsId')
    },
    mounted() {
      this.reCustomerList()
      this.getCurrentIsTaskUser()
      this.getUserChangeTimeLimit1()
    }
  }
</script>
<style lang="scss" scoped>
  .del_user {
    .tips {
      text-align: center;
      margin-bottom: 15px;
      background-color: rgba(254, 252, 236, 1);
      width: auto;
      margin-left: 100px;
      line-height: 32px;

      .tips_icon {
        font-size: 20px;
        color: #0f42a7;
      }

      .AssignCustomers_name {
        margin-left: 10px;
        cursor: pointer;
        color: #0f42a7;
      }
    }
  }
</style>
